﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotNetOpenAuth.Messaging;
using StructureMap;

namespace Yala.Client.Web.MVC.Authentication.DotNetOpenAuth
{
    public class DotNetOpenAuthManager : IAuthenticationManager
    {
        private IDotNetOpenAuthOpenIdRelyingParty _openIdRelyingParty;
        public DotNetOpenAuthManager(IDotNetOpenAuthOpenIdRelyingParty openIdRelyingParty)
        {
            _openIdRelyingParty = openIdRelyingParty;
        }

        public IAuthenticationResponse Authenticate(string openIdProdiver)
        {
            var result = ObjectFactory.GetInstance<IAuthenticationResponse>();
            var response = _openIdRelyingParty.GetResponse();

            if (response.IsNullResponse)
            {
                try
                {
                    var actionResult = _openIdRelyingParty.CreateRequest(openIdProdiver);
                    result.ActionResult = actionResult;
                    result.Status = AuthenticationStatus.RedirectToOpenIdProvider;
                    return result;
                } catch (DotNetOpenAuthProtocolException protocolException)
                {
                    result.Exception = protocolException;
                    result.Status = AuthenticationStatus.ProtocolException;
                    return result;
                }
            }
            else
            {
                return response;
            }
            
        }
    }
}
